package com.controller;

import com.entity.MaintenanceWorkType;
import com.service.MaintenanceWorkTypeService;
import com.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/maintenance/work/type")
public class MaintenanceWorkTypeController {

    @Autowired
    private MaintenanceWorkTypeService maintenanceWorkTypeService;

    @PostMapping
    public MaintenanceWorkType create(@RequestBody MaintenanceWorkType maintenanceWorkType) {
        return maintenanceWorkTypeService.save(maintenanceWorkType);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable(value = "id") Integer id) {
        maintenanceWorkTypeService.deleteById(id);
    }

    @PutMapping("/{id}")
    public MaintenanceWorkType update(@PathVariable(value = "id") Integer id, @RequestBody MaintenanceWorkType maintenanceWorkType) {
        maintenanceWorkType.setId(id);
        return maintenanceWorkTypeService.save(maintenanceWorkType);
    }

    @GetMapping("/{id}")
    public MaintenanceWorkType detail(@PathVariable(value = "id") Integer id) {
        return maintenanceWorkTypeService.findById(id).orElse(null);
    }

    @GetMapping("/page")
    public Page<MaintenanceWorkType> page(@RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "10") int pageSize,
                       @RequestParam(required = false) String typeName) {
        Page<MaintenanceWorkType> page;
        if (typeName != null && !typeName.isEmpty()) {
            page = maintenanceWorkTypeService.findByTypeNameContaining(typeName, pageNum, pageSize);
        } else {
            page = maintenanceWorkTypeService.findAll(pageNum, pageSize);
        }
        return page;
    }
}